<template>
    <div class="regist-client-dialog-view">

        <el-dialog
                v-model="dialogShow"
                :close-on-click-modal="false"
                width="900px"
                title="注册跟进客户"
                @closed="close"
        >

            <el-form
                    :rules="rule"
                    ref="refForm"
                    :model="formData"
                    label-width="120px"
                    size="small"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="关联营销任务">
<!--                            <seller-task ref="sellerTaskRef" :headId="formData.headId" @confirm="sellerConfirm" is-position position="bottom-start">-->
<!--                                <el-select v-model="formData.planName" :disabled="false" clearable-->
<!--                                           placeholder="请选择关联营销任务" style="width: 100%" @clear="sellerClear" @focus="sellerFocus">-->
<!--                                    <template #empty />-->
<!--                                </el-select>-->
<!--                            </seller-task>-->

                            <el-input
                                    ref="refInput"
                                    v-model="formData.saleTaskNo"
                                    placeholder="请输入营销任务"
                                    clearable
                                    @clear="taskClear"
                                    @blur="taskBlur"
                                    @focus="taskFocus"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="通用名" prop="productPopularName" style="width: 100%">
                            <product-popover
                                    :searchs="formData.productPopularName"
                                    :disabled="disabled || formData.saleTaskId > 0"
                                    @confirm="productConfirm"
                            >
                                <el-input
                                        v-model="formData.productPopularName"
                                        :disabled="formData.saleTaskId > 0"
                                        placeholder="请输入产品名称"
                                />
                            </product-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品名" style="width: 100%">
                            <el-input
                                    v-model="formData.productName"
                                    placeholder="请输入商品名"
                                    disabled
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="包装规格" style="width: 100%">
                            <el-input
                                    v-model="formData.packSpecs"
                                    placeholder="请选择包装规格"
                                    disabled
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生产厂家" style="width: 100%">
                            <el-input
                                    v-model="formData.producer"
                                    placeholder="请选择生产厂家"
                                    disabled
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户类型" style="width: 100%" prop="customerType">
                            <el-select
                                    :disabled="formData.saleTaskId > 0"
                                    v-model="formData.customerType"
                                    style="width: 100%"
                                    @change="typeChange"
                                    placeholder="请选择客户类型">
                                <el-option
                                        v-for="item in typeOptions.filter(a=>a.value != 4)"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="formData.customerType == 1">
                        <el-form-item label="代理名称" prop="objectName" style="width: 100%">
                            <el-autocomplete
                                    :disabled="!formData.productId"
                                    v-model="formData.objectName"
                                    style="width: 100%"
                                    placeholder="请输入代理商名称"
                                    :fetch-suggestions="querySearchAsyncAgent"
                                    @select="handleSelectAgent"
                            >
                                <template #default="{ item }">
                                    <div class="distributeName" v-if="item.agentType == 'agent'">{{ item.agentName }}</div>
                                    <div class="distributeName" v-else>{{ item.userName }}</div>
                                </template>
                            </el-autocomplete>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="formData.customerType == 1">
                        <el-form-item v-if="isNot" label="未找到代理商">
                            <el-button type="text" @click="onCreate" style="margin: 0 10px">新建代理商</el-button>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="formData.customerType == 2">
                        <el-form-item label="商销客户" prop="objectName" style="width: 100%">
                            <el-autocomplete
                                    v-model="formData.objectName"
                                    style="width: 100%"
                                    placeholder="请输入商销客户名称"
                                      :fetch-suggestions="querySearchAsyncShangxiao"
                                      @select="handleSelectShangxiao"
                        >
                            <template #default="{ item }">
                                <div class="distributeName">{{ item.sellerName }}</div>
                            </template>
                            </el-autocomplete>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="formData.customerType == 2">
                        <el-form-item v-if="isNot" label="未找到商销客户">
                            <el-button type="text" @click="onCreate1" style="margin: 0 10px">新建商销客户</el-button>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="formData.customerType == 3">
                        <el-form-item label="终端" prop="objectName" style="width: 100%">
                            <el-autocomplete
                                    v-model="formData.objectName"
                                    style="width: 100%"
                                    placeholder="请输入终端名称"
                                    :fetch-suggestions="querySearchTerminal"
                                    @select="handleSelecTerminal"
                            >
                                <template #default="{ item }">
                                    <div class="distributeName">{{ item.terminalName }}</div>
                                </template>
                            </el-autocomplete>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="formData.customerType == 3">
                        <el-form-item v-if="isNot" label="未找到终端">
                            <el-button type="text" @click="onCreate2" style="margin: 0 10px">新建终端</el-button>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item style="width: 100%" label="开发跟进期限" prop="followUpTime">
                            <date-picker
                                    style="width: 100%"
                                    v-model:date="formData.followUpTime"
                                    :disabled-date="disabledDate"
                                    placeholder="请选择期限"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责跟进职员" style="width: 100%">
                            <el-input
                                    v-model="formData.headName"
                                    placeholder="请选择负责跟进职员"
                                    disabled
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button
                            class="border-btn"
                            size="small"
                            @click="close"
                    >取消</el-button>
                    <el-button
                            class="main-btn"
                            size="small"
                            type="primary"
                            @click="confirm"
                    >确定</el-button>
                </div>
            </template>
        </el-dialog>

        <fromDialog ref="fromDialog"/>

        <newForm ref="newFormRef"/>

        <rule-form ref="ruleForm" :sub="{boole: false,title: '保存'}" type-str="create" form-type="2"/>

        <chanceTaskDialog ref="taskDialog" @confirm="taskConfirm"/>

    </div>
</template>

<script>
    import {crmStore} from "../../../../store";
    import { defineComponent, defineAsyncComponent, reactive, toRefs, inject, getCurrentInstance, ref } from 'vue'
    export default defineComponent({
        name: "registClientDialog",
        emits:['success'],
        components:{
            fromDialog : defineAsyncComponent(
                ()=>import('../../customer/modules/fromDialog.vue')
            ),
            newForm:defineAsyncComponent(
                ()=>import('../../customer/shangPin/modules/newForm.vue')
            ),
            ruleForm:defineAsyncComponent(
                ()=>import('../../customer/terminal/modules/ruleForm.vue')
            ),
            chanceTaskDialog:defineAsyncComponent(
                ()=>import('../../modules/chanceTaskDialog.vue')
            ),
        },
        setup(props,{emit}){
            const checkObject = async (rule, value, callback) => {
                console.log(2222222,value)
                if (!value) {
                    callback(new Error('请选择客户'))
                } else {
                    console.log(333333333,data.formData.objectId)
                    if (!data.formData.objectId){
                        callback(new Error('请选择客户'))
                    }else {
                        let pam = {
                            customerType:data.formData.customerType,
                            productId:data.formData.productId,
                            objectId:data.formData.objectId,
                        }
                        const res = await api.task.TASK_CUSTOMER_ISREGISTER(pam)
                        if (!res.code && res.data.isRegister){
                            callback()
                        }else if (!res.data.isRegister){
                            callback('客户已在跟进中，无法重复注册')
                        }
                    }
                }
            }

            const currentInstance = getCurrentInstance()
            const api = inject('api')
            const userInfo = crmStore.getters['user/userInfo']
            const typeOptions = crmStore.getters['dictionary/getDictionary']['client_type']
            const rule = ref({
                productPopularName: [
                    { required: true, message: '请选择产品', trigger: 'change' },
                ],
                customerType: [
                    { required: true, message: '请选择客户类型', trigger: 'change' },
                ],
                objectName:[
                    {required: true, validator: checkObject, trigger: 'change',}
                ],
                followUpTime:[
                    {
                        type: 'date',
                        required: true,
                        message:'开发跟进期限',
                        trigger: 'change',
                    },
                ]
            })

            var data = reactive({
                disabled:false,
                dialogShow:false,
                sellerTaskRef:null,
                newFormRef:null,
                ruleForm:null,
                refForm:null,
                isNot:false,
                formData:{
                    selectName:'',
                    taskName:'',
                    customerNo:'',
                    objectName:'',
                    objectId:'',
                    saleTaskId:'',
                    saleTaskNo:'',
                    customerType:'',
                    headId:0,
                    planName:'',
                    planInfoDetailId:0,
                    productPopularName:'',
                    productId:0,
                    productName:'',
                    packSpecs:'',
                    producer:'',
                    sellUnit:'',
                    agentName:'',
                    agentId:0,
                    agentType:'',
                    allocationAgentId:0,
                },
                fromDialog:null,
                taskDialog:null,
                refInput:null,
                taskRelationId:0,
            })

            const sellerClear = () => {
                data.formData.planInfoDetailId = 0
                data.formData.planName = ''
            }

            const sellerFocus = () => {
                data.sellerTaskRef.openPopover();
            }

            const sellerConfirm = (item) => {
                data.isPlan = true
                data.formData.planInfoDetailId = item.planDetail.id
                data.formData.planId = item.planInfo.id
                data.formData.planName = item.planInfo.planName
                data.formData.productId = item.planInfo.productId
                data.formData.productPopularName = item.planInfo.productPopularName
                data.formData.productName = item.planInfo.productName
                data.formData.packSpecs = item.planInfo.packSpecs
                data.formData.producer = item.planInfo.producer
                data.formData.sellUnit = item.planInfo.sellUnit
            }

            const productConfirm = (val) => {
                data.formData.productId = val.id
                data.formData.productPopularName = val.productPopularName
                data.formData.productName = val.productName
                data.formData.approvalNumber = val.approvalNumber
                data.formData.packSpecs = val.packSpecs
                data.formData.producer = val.producer
                data.formData.sellUnit = val.sellUnit

            }

            const taskConfirm = (val) => {
                console.log(val)
                data.taskRelationId = val.taskRelationId
                data.formData.allocationAgentId = val.id
                data.formData.saleTaskId = val.saleTaskId
                data.formData.saleTaskNo = val.taskNo

                data.formData.productId = val.productId
                data.formData.productPopularName = val.productPopularName
                data.formData.productName = val.productName
                data.formData.approvalNumber = val.approvalNumber
                data.formData.packSpecs = val.packSpecs
                data.formData.producer = val.producer
                data.formData.sellUnit = val.sellUnit
                console.log(val.taskType)
                if (val.taskType == 1 || val.taskType == 2){
                    data.formData.customerType = '1'
                }else if (val.taskType == 3){
                    data.formData.customerType = '3'
                }else if (val.taskType == 4){
                    data.formData.customerType = '2'
                }
                data.formData.objectName = '';
                data.formData.objectId = '';
            }

            const taskBlur = () => {
                if (!data.formData.selectName) {
                    data.formData.saleTaskId = 0
                    data.formData.taskName = ''
                    data.formData.saleTaskNo = ''
                }
                if (data.formData.saleTaskNo) {
                    data.formData.selectName = data.formData.saleTaskNo
                }
            }

            const taskFocus = () => {
                // data.chancePop.openPopover()
                data.taskDialog.openDialog()
                data.refInput.blur()
            }

            const taskClear = () => {
                data.formData.saleTaskId = 0
                data.formData.allocationAgentId = 0
                data.formData.saleTaskNo = ''
                data.taskRelationId = 0
            }

            // 获取终端
            const querySearchTerminal = async (queryString, cb) => {
                let results = [];
                let cityCode = []
                // if (data.openForm.planId && data.planArea.length){
                //     cityCode = [data.planArea[0].regionCode]
                // }

                const res = await api.terminal.TERMINAL_DIRECT({
                    selectStr: queryString,
                    cityCode:cityCode,
                    taskRelationId:data.taskRelationId,
                });
                if (res.code === 0) {
                    results = res.data.list || [];
                    if (queryString && !results.length){
                        data.isNot = true
                    }else {
                        data.isNot = false
                    }
                }else {
                    currentInstance.proxy.customMessage({type:"error",message:res.msg})
                    cb([])
                }
                cb(results);
            };

            const handleSelecTerminal = (val) => {
                if (val) {
                    data.formData.objectName = val.terminalName;
                    data.formData.objectId = val.id;
                    data.formData.customerNo = val.terminalNo

                }
            };

            //获取商销客户
            const querySearchAsyncShangxiao = async(queryString, cb) => {
                if (!queryString){
                    data.isNot = false
                    cb([])
                }else {
                    const a = {
                        keyWord: queryString,
                    }
                    let results = []
                    const res = await api.businessAgreement.BUSINESSAGREEMENT_SHANGPIN_LIST(queryString)
                    if (!res.code && res.data) {
                        results = res.data.list || []
                        if ((!res.data.list || !res.data.list.length) && queryString) {
                            data.isNot = true
                        } else {
                            data.isNot = false
                        }
                    }
                    cb(results)
                }
            }

            // 代理商事件
            const handleSelectShangxiao = (val) => {
                data.formData.objectId = val.id
                data.formData.objectName = val.sellerName
                data.formData.customerNo = val.sellerNumber
            }

            // 获取代理商列表
            const querySearchAsyncAgent = async(queryString, cb) => {
                if (!queryString){
                    data.isNot = false
                    cb([])
                }else {
                    const a = {
                        keyWord: queryString,
                    }
                    let results = []
                    const res = await api.editorial.EDITORIAL_KEYWORDS(a)
                    if (!res.code && res.data) {
                        results = res.data.list || []
                        if ((!res.data.list || !res.data.list.length) && queryString){
                            data.isNot = true
                        }else {
                            data.isNot = false
                        }
                    }
                    cb(results)
                }
            }

            // 代理商事件
            const handleSelectAgent = (val) => {
                console.log(1111111111,val)
                data.formData.objectId = val.id
                data.formData.objectName = val.agentName
                data.formData.customerNo = val.agentNumber
                data.formData.agentType = val.agentType
                if (val.agentType != 'agent'){
                    data.formData.objectName = val.userName
                }
                console.log(data.formData)
                data.refForm.validateField('objectName')
            }

            const close = () => {
                data.disabled = true
                data.taskRelationId = 0
                data.formData = {
                    selectName:'',
                    taskName:'',
                    customerNo:'',
                    objectName:'',
                    objectId:'',
                    saleTaskId:'',
                    customerType:'',
                    headId:0,
                    planName:'',
                    planInfoDetailId:0,
                    productPopularName:'',
                    productId:0,
                    productName:'',
                    packSpecs:'',
                    producer:'',
                    sellUnit:'',
                    agentName:'',
                    agentId:0,
                    agentType:'',
                    followUpTime:'',
                }
                data.dialogShow = false
                setTimeout(()=>{
                    data.disabled = false
                    data.refForm.clearValidate()
                },500)
            }

            const confirm = () => {
                data.refForm.validate((val)=>{
                    if (val){
                        let a = {...data.formData}
                        a.allocationAgentId = Number(a.allocationAgentId)
                        a.saleTaskId = Number(a.saleTaskId)
                        a.objectId = Number(a.objectId)
                        a.headId = Number(a.headId)
                        a.productId = Number(a.productId)

                        api.task.TASK_CUSTOMER_REGISTER(a).then(res=>{
                            if (!res.code){
                                currentInstance.proxy.customMessage({type:'success',message:'成功'})

                                emit('success')
                                close()
                            }else {
                                currentInstance.proxy.customMessage({type:'error',message:res.msg})
                            }
                        })
                    }
                })
            }

            const open = () => {
                data.formData.headId = userInfo.ID
                data.formData.headName = userInfo.realName
                let d = new Date();
                d.setMonth(d.getMonth() +1);
                data.formData.followUpTime = d

                data.dialogShow = true
            }

            const onCreate = () => {
                data.fromDialog.open()
            }

            const onCreate1 = () => {
                data.newFormRef.open("新建商销客户", null);
            }

            const onCreate2 = () => {
                data.ruleForm.open(null, 1);
            }

            const typeChange = () => {
                data.formData.objectId = 0
                data.formData.objectName = ''
            }

            const disabledDate = (time) => {
                return !(time.getTime() > Date.now())
            }

            return{
                ...toRefs(data),
                typeOptions,
                rule,

                close,
                confirm,
                open,
                sellerClear,
                sellerFocus,
                sellerConfirm,
                productConfirm,
                querySearchAsyncAgent,
                handleSelectAgent,
                onCreate,
                onCreate1,
                onCreate2,
                typeChange,
                disabledDate,
                querySearchAsyncShangxiao,
                handleSelectShangxiao,
                querySearchTerminal,
                handleSelecTerminal,
                taskBlur,
                taskFocus,
                taskClear,
                taskConfirm,
            }
        }
    })
</script>

<style scoped>

</style>
